package com.MusicWeb.servlet;

import com.MusicWeb.entity.Music;
import com.MusicWeb.entity.User;
import com.MusicWeb.service.UsermusicService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@WebServlet("/upload")
// 允许表单分段的注解（必须）
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private String dirPath;
    UsermusicService usermusicService=new UsermusicService();

    @Override
    public void init() throws ServletException {
        super.init();
        dirPath = this.getServletContext().getInitParameter("uploadDir");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Integer id=Integer.parseInt(req.getParameter("uid"));

//        User user= (User) req.getSession().getAttribute("user");

        String user_name=req.getParameter("user_name");
        String name=req.getParameter("music_name");
        String singer=req.getParameter("music_singer");
        String text=req.getParameter("music_text");

        // 获取表单中文件那部分内容，跟input框的name属性相同
        Part part = req.getPart("zhuxm");
        // 获取这一部分的输入流
        InputStream is = part.getInputStream();
        // 获取文件名
        String fileName = part.getSubmittedFileName();
        // 生成保存在服务器的文件名，用当前时间来命名避免重复
        String saveFileName = new Date().getTime() +
                fileName.substring(fileName.lastIndexOf("."));

        FileOutputStream fos = new FileOutputStream(dirPath + saveFileName);
        // 读取输入流的内容，写到输出流里
        byte[] ch = new byte[1024];
        int len = 0;
        while ((len = is.read(ch)) > 0) {
            fos.write(ch, 0, len);
        }
        // 刷新并关闭输入、输出流
        fos.flush();
        fos.close();
        is.close();
        // 提示一下文件名
        resp.getWriter().print(saveFileName);

        Music music=new Music();
        //用户
        music.setUid(id);
        //用户名字
        music.setUser_name(user_name);
        //歌名
        music.setMusic_name(name);
        //歌手
        music.setMusic_singer(singer);
        //简介
        music.setMusic_text(text);
        //下载地址
        music.setMusic_url(saveFileName);
//        usermusicService.instermusic(music);
        if (usermusicService.instermusic(music)!=null){
            req.getSession().setAttribute("msg", "上传成功");
            resp.sendRedirect(req.getContextPath()+"/FunctionPage/ShareMusic.jsp");
        }else {
            req.getSession().setAttribute("msg", "上传失败");
            resp.sendRedirect(req.getContextPath()+"/FunctionPage/ShareMusic.jsp");
        }
    }
}
